#include "stdafx.h"
#include "NetManager.h"
#include <boost/bind.hpp>

#ifdef WIN32
#ifdef _DEBUG
#pragma comment(lib, "libprotobufD")
#else
#pragma comment(lib, "libprotobuf")
#endif
#pragma comment(lib, "net_module")
#pragma comment(lib, "logutil")
#endif

CNetManager::CNetManager(void)
{
	m_pNetworkModule = NULL;
	m_pConnector = NULL;
	m_pWorkThread = NULL;
	m_bTerminated = true;
}


CNetManager::~CNetManager(void)
{
	_StopThread();
	destroy_net_module();
}

bool CNetManager::Init()
{
	m_pNetworkModule = get_net_module();

	m_pConnector = m_pNetworkModule->create_connector();
	m_pConnector->set_event_handler(&m_oConnectorEventHandler);
	m_oConnectorEventHandler.SetConnector(m_pConnector);
	return m_pNetworkModule && m_pConnector;
}

bool CNetManager::Connect( const char * szIPAddress, const char * szPort )
{
	_StopThread();
	try
	{
		m_pConnector->connect(szIPAddress, szPort);
		m_bTerminated = false;
		m_pWorkThread = new boost::thread(boost::bind(&CNetManager::_StartWork, this));
		return true;
	}
	catch(...)
	{
		return false;
	}
}

void CNetManager::_StopThread()
{
	m_bTerminated = true;
	if (m_pWorkThread)
	{
		m_pWorkThread->join();
		delete m_pWorkThread;
		m_pWorkThread = NULL;
	}
}

void CNetManager::_StartWork()
{
	while (!m_bTerminated)
	{
		m_pNetworkModule->run();
	}
}
